(function () {
    let flag = false
    let dragFlag = false
    let str = ''
    let iconTimeId = null
    const mapType = {
        "zh": '中文',
        'yue': '粤语',
        'kor': '韩语',
        "en": '英文',
        'jp': '日语',
        'de': '德语',
        'it': '意大利语'
    }

    window.addEventListener('mouseup', function (e) {
        e && e.stopPropagation()
        if (!window.getSelection) return false
        str = window.getSelection().toString()
        if (!str || flag || dragFlag) return clearIcon('#_img_icon_')
        insertIcon(e.clientX, e.clientY)
    }, false)

    function insertIcon(x, y) {
        if (!x || !y) return
        const img = document.createElement('img')
        img.id = '_img_icon_'
        img.style.width = 28 + 'px'
        img.style.height = 28 + 'px'
        img.src = chrome.runtime.getURL('assets/icon/icon48.png')
        img.style.position = 'fixed'
        img.style.top = y + 'px'
        img.style.left = x + 'px'
        img.onclick = iconTap
        document.body.append(img)
        flag = true
        iconTimeId = setTimeout(() => {
            clearIcon("#_img_icon_")
        }, 3000)
    }

    function clearIcon(id) {
        clearTimeout(iconTimeId)
        setTimeout(() => {
            const icon = document.querySelector(id)
            icon && document.body.removeChild(icon)
            flag = false
            iconTimeId = null
        }, 16)
    }

    function iconTap(e) {
        if (!flag) return false
        e && e.stopPropagation()
        insertPlan(e)
        getData(str)
    }
    function strToDom(str) {
        const parser = new DOMParser()
        const Fragment = document.createDocumentFragment()
        const children = parser.parseFromString(str, "text/html").body.children
        Array.from(children).forEach(v => {
            Fragment.appendChild(v)
        })
        return Fragment
    }

    function initHead() {
        const head = getDom(".w_head")
        const children = `
            <div class="w_headTitle"></div>
            <img class="w_clear" src="${chrome.runtime.getURL("assets/icon/close.png")}"/>
    `
        head.appendChild(strToDom(children))
        getDom('.w_headTitle').innerHTML = str
        const clear = getDom('.w_clear')
        clear.onclick = () => {
            clearIcon('#w_box')
            str = ''
        }

    }
    function initBody() {
        const body = getDom(".w_text")
        const children = `
    <div class="w_tool">
       <p class="w_title">
       </p>
       <img class="w_speek" src="${chrome.runtime.getURL('assets/icon/pay.png')}" />
    </div>
    <div class="w_translate"></div>
   `
        body.appendChild(strToDom(children))
        const w_title = getDom('.w_title')
        const select = initSelectType()
        w_title.appendChild(select)
        getDom(".w_tool .w_speek").onclick = speek

    }
    function initFooter() {
        const footer = getDom('.w_footer')
        footer.innerHTML = '百度翻译~~~'
    }

    function insertPlan(e) {
        if (isPlan()) return
        const x = e.clientX
        const y = e.clientY
        const box = document.createElement('div')
        const ElStr = `
        <div class="w_head">
        </div>
        <div class="w_body">
            <div class="w_text">
            </div>
        </div>
        <div class="w_footer"></div>
    `
        box.className = 'w_box'
        box.id = 'w_box'
        box.style.position = 'fixed'
        box.style.top = y + 'px'
        box.style.left = x + 'px'
        box.innerHTML = ElStr
        clearIcon('#_img_icon_')
        document.body.appendChild(box)
        initHead()
        initBody()
        initFooter()
        drag()
        getDom('#w_box .w_body').addEventListener('mouseup', (e) => {
            e.stopPropagation()
        }, false)
    }

    function isPlan() {
        return getDom('#w_box')
    }
    function typeChange(e) {
        const to = e.target.value
        getData(str, to)

    }
    function initSelectType() {
        const select = document.createElement('select')
        select.id = 'w_select'
        const options = []
        Object.keys(mapType).forEach(key => {
            const str = `<option value=${key}>${mapType[key]}</option>`
            options.push(str)
        })
        select.innerHTML = options.join('')
        select.onchange = typeChange
        select.value = ''
        return select
    }

    function drag() {
        const box = getDom('#w_box')
        const head = getDom('.w_head')
        let oldX, oldY, offsetLeft = null
        if (!box) return
        head.addEventListener('mousedown', function (e) {
            e.preventDefault()
            dragFlag = true
            oldY = e.clientY
            oldX = e.clientX
            offsetLeft = box.offsetLeft
            offsetTop = box.offsetTop
            document.addEventListener('mousemove', move)
            document.addEventListener('mouseup', remove)
        })

        function move(e) {
            e.preventDefault()
            box.style.top = e.clientY - oldY + +offsetTop + 'px'
            box.style.left = +e.clientX - +oldX + +offsetLeft + 'px'
        }
        function remove() {
            setTimeout(() => {
                dragFlag = false
                document.removeEventListener('mousemove', move)
                document.removeEventListener('mouseup', remove)
            }, 16)
        }
    }

    function getData(q, to) {
        console.log(to)
        return new Promise((resolve, reject) => {
            chrome.runtime.sendMessage({
                type: "getData",
                playload: {
                    q, to
                },
            }, callback)

            function callback({ data }) {
                const { trans_result = [], from, to } = data
                console.log(data)
                setTranslateResult(trans_result)
                setType(to)
                resolve(data)
            }
        })
    }

    function setTranslateResult(translateResult) {
        const plan = getDom('.w_translate')
        plan.innerHTML = translateResult[0] && translateResult[0].dst
    }

    function setType(type) {
        if (!type) return
        const select = getDom('.w_title #w_select')
        select.value = type
    }

    function sendMessage(data, callback) {
        return new Promise((resolve, reject) => {
            chrome.runtime.sendMessage(data, function (res) {
                callback && callback(res)
                res.success ? resolve(res.data) : reject(res.error)
            })
        })
    }
    function speek(str) {
        try {
            const speehInstance = new SpeechSynthesisUtterance(str)
            speechSynthesis.speak(speehInstance)
        } catch { }
    }
    function getDom(query) {
        return document.querySelector(query)
    }

})()